package uk.ac.open.kmi.dyniqx.repositories;

import java.net.URLEncoder;
import java.io.IOException;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import org.apache.log4j.Logger;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;

import uk.ac.open.kmi.dyniqx.storages.Storage;
import uk.ac.open.kmi.dyniqx.wrappers.QueryWrapper;

public class YahooImagesRepository implements Repository {

	private Storage storage;
	
	public Logger logger = Logger.getLogger("uk.ac.open.kmi.dyniqx.repositories.YahooImagesRepository");
	
	public YahooImagesRepository() {
		this.logger.debug("YahooImagesRepository instance created.");
	}
	
	@SuppressWarnings("unchecked")
	public void performQuery(String queryString) {
		
		String baseUrl = "http://search.yahooapis.com/ImageSearchService/V1/imageSearch?appid=SoE1x_TV34HSVv56Bm7BuXyT4wFLqNoVKy7OvZVOFEyry6JMENE4jIspIV5TcHSj&query=";
		
		/* Open University proxy Settings */
 
		System.getProperties().put( "proxySet", "true" );
		System.getProperties().put( "proxyHost", "wwwcache" );
		System.getProperties().put( "proxyPort", "80" );
		System.setProperty("java.net.useSystemProxies","true");
		
		SAXBuilder parser = new SAXBuilder();

		try {

			Document doc = parser.build(baseUrl + URLEncoder.encode(queryString, "UTF-8"));

	    	logger.debug(baseUrl + URLEncoder.encode(queryString, "UTF-8"));		
			Element root = doc.getRootElement();

			String count = root.getAttribute("totalResultsAvailable").getValue();
	    	WebContext wctx = WebContextFactory.get();
	    	logger.debug(count);
	    	
	    	QueryWrapper newQuery = new QueryWrapper(queryString, "YIm", Integer.parseInt(count), 0);
	    	
	    	this.storage.getQueryWrapper().add(newQuery);
	    	
	    	Thread t = new YahooImagesThread(this.storage, wctx, queryString, Integer.parseInt(count));
	    	t.setName("YIm" + "-" + wctx.getSession().getId() + "-" + (System.currentTimeMillis() % 1000000));
	    	t.start();
	    		    	
	    	this.storage.updateGrid();	    		    	
			
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void setStorage(Storage storage) {
		this.storage = storage;
	}	
	
	public Storage getStorage() {
		return this.storage;
	}
}
